package com.jd.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.jd.util.StringUtils;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.qcloudsms.SmsSingleSenderResult;
import com.jd.entity.UserEntity;
import com.jd.entity.UserEntity;
import com.jd.service.UserService;
import com.jd.util.IdUtil;
import com.jd.util.SmsServiceUtil;

@Controller
@RequestMapping("/wechat")
public class LoginController {

	@Autowired
    private WxMpService wxMpService;
    
    @Autowired
    private UserService userService;
    
	@RequestMapping("/authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl,HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{

		//response.sendRedirect("http://116.62.114.248:8090/game/html/UserInfo.html?New=0");

		String onUserId = request.getParameter("id");
		//type=0(推广员) type=1(玩家)
		String type = request.getParameter("type");
        String url = "http://www.bfwcg.com/game/wechat/userInfo?onUserId="+onUserId+"&type="+type;
        String redirectURL = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, URLEncoder.encode(returnUrl));
        System.out.println(redirectURL+".....................................................");
        return "redirect:"+redirectURL;
    }
	
	@RequestMapping("/userInfo")
    public void userInfo(@RequestParam("code") String code,
                           @RequestParam("state") String returnUrl,
                           HttpServletRequest request,HttpServletResponse response) throws Exception {
    	HttpSession session = request.getSession();
       WxMpOAuth2AccessToken wxMpOAuth2AccessToken;
       try {
    	   //上级推广员
    	   String onUserId = request.getParameter("onUserId");
    	   System.out.println(onUserId+"+++++++++++++++++++++++++++++++++++++++++++++++++++");
    	   System.out.println(onUserId+"+++++++++++++++++++++++++++++++++++++++++++++++++++");
    	   System.out.println(onUserId+"+++++++++++++++++++++++++++++++++++++++++++++++++++");
    	   System.out.println(onUserId+"+++++++++++++++++++++++++++++++++++++++++++++++++++");
    	   //邀请身份
    	   String type = request.getParameter("type");
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
            //获取微信用户信息
            WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
            String openId = wxMpUser.getOpenId();
            session.setAttribute("openId", openId);
            System.out.println("++++++++++++++++++++++++"+openId);
            System.out.println("++++++++++++++++++++++++"+openId);
            System.out.println("++++++++++++++++++++++++"+openId);
            String nickname = wxMpUser.getNickname();
            session.setAttribute("nickname", nickname);
            System.out.println("++++++++++++++++++++++++"+nickname);
            System.out.println("++++++++++++++++++++++++"+nickname);
            System.out.println("++++++++++++++++++++++++"+nickname);
            System.out.println("++++++++++++++++++++++++"+nickname);
            System.out.println("++++++++++++++++++++++++"+nickname);
            System.out.println("++++++++++++++++++++++++"+openId);
            String headImgUrl = wxMpUser.getHeadImgUrl();
            //openId为用户唯一标识 
           UserEntity user = new UserEntity();
	       user.setWxAvatar(headImgUrl);
	       user.setOpenId(openId);
	       user.setWxName(nickname);
	       UserEntity userEntity = userService.userByOpenId(openId);
	       System.out.println("++++++++++++++++++++++++"+userEntity);
	       //判断用户付费情况
	       if(userEntity!=null && !userEntity.equals("")){
	       	//修改头像和昵称
	        userService.updateUserLogo(user);
	        String userId=userEntity.getId();
	        session.setAttribute("userId",userId);
	    	System.out.println(userEntity.getId()+"++++++++++++++++++++++++++++++++++++");
	    	System.out.println(userEntity.getId()+"++++++++++++++++++++++++++++++++++++");
	    	System.out.println(userEntity.getId()+"++++++++++++++++++++++++++++++++++++");
	    	System.out.println(userEntity.getId()+"++++++++++++++++++++++++++++++++++++");
	    	System.out.println(userEntity.getId()+"++++++++++++++++++++++++++++++++++++");
	    	System.out.println(userEntity.getId()+"++++++++++++++++++++++++++++++++++++");
	    	System.out.println(userEntity.getId()+"++++++++++++++++++++++++++++++++++++");
	    	//进主页
	    	response.sendRedirect("http://www.bfwcg.com/game/html/UserInfo.html?New=1&avatar="+headImgUrl);
            }else{
            	session.setAttribute("nickname", nickname);
            	//完善个人信息
            	response.sendRedirect("http://www.bfwcg.com/game/html/UserInfo.html?New=0&openId="+openId+"&onUserId="+onUserId+"&avatar="+headImgUrl+"&type="+type+"&wxName="+nickname);
            }
        } catch (Exception e) {
            throw new Exception(e);
        }
    }
	@RequestMapping("/insertUser")
	@ResponseBody
	public String insertUser(HttpServletRequest request,HttpServletResponse response) throws Exception {
		HttpSession session = request.getSession();
		 String code = request.getParameter("code");
		 String phone = request.getParameter("phone");
		String remark1 = request.getParameter("remark1");
		 //邀请身份
 	     String type = request.getParameter("type");
 	     String openId = request.getParameter("openId");
 	     String avatar = request.getParameter("avatar");
 	     String wxName = request.getSession().getAttribute("nickname").toString();
 	     //上级推广员
 	     String onUserId = request.getParameter("onUserId");
		 String phoneCode = request.getSession().getAttribute(phone).toString();
		 if(phoneCode.equals(code)){
			 UserEntity user = userService.getUserByPhone(phone);
			 //如果电话号和库里的数据重复直接修改openId
			 if(user!=null && !user.equals("")){
				HashMap<String, String> phoneMap = new HashMap<String,String>();
				phoneMap.put("phone", phone);
				phoneMap.put("openId", openId);
				userService.updateOpenId(phoneMap);
				session.setAttribute("userId", user.getId());
				return "注册成功";
			 }else{
				UserEntity userEntity = new UserEntity();
				String id=IdUtil.getIdByUUId();
				if(onUserId.equals("") || onUserId==null || onUserId.equals("null")){
					onUserId=null;
				}
				userEntity.setId(id);
				userEntity.setOnUserId(onUserId);
				userEntity.setOpenId(openId);
				if(type.equals("") || type==null ||  type.equals("null")){
					type="2";
				}
				userEntity.setIdentity(type);
				userEntity.setWxAvatar(avatar);
				userEntity.setWxName(wxName);
				userEntity.setExaTime(new Date());
				userEntity.setPhone(phone);
				userEntity.setCreateBy(id);
				userEntity.setCreateTime(new Date());
				userEntity.setDelflag("0");

				userEntity.setRemark1(remark1);
				String zfc = StringUtils.zfc(8);
				userEntity.setRemark(zfc);
				userService.insertUser(userEntity);
				session.setAttribute("userId", id);
				return "注册成功";
			 }
		 }else{
			 return "验证码不正确";
		 }
	}
	
	 /**
	   * 发送短信验证码
	   * 
	   * */
	  @RequestMapping("/sendMsg")
	  @ResponseBody
	  public String sendMsg(String phone, HttpServletRequest request) {
	     try {
	        // 发送短信验证码
	        // 随机验证码6位
	        String code = (int) ((Math.random() * 9 + 1) * 100000) + "";
	        // String code = "111111";
	        ArrayList<String> params = new ArrayList<String>();
	        // 订单号
	        params.add(code);
	        // 短信模板，手机号,自定义参数
	        Integer aa = 845861;
	        SmsSingleSenderResult result = SmsServiceUtil.txSendSms(aa, phone,params);
	        if (result.errMsg.equals("OK")) {
	           // if (true) {
	           HttpSession session = request.getSession();// 保存session
	           session.setAttribute(phone, code);// 随机验证码
	           //埋点 插入获取验证码次数 type = 4
	           //tbStatisticalService.PointCount();
	           return "验证码发送成功";// 返回200成功
	        }
	        return "验证码发送成功";
	        //return ResultUtil.error("验证失败");
	     } catch (Exception e) {
	        // TODO Auto-generated catch block
	        e.printStackTrace();
	        return "发送验证码失败";
	     }
	  }
}
